package com.storage.web.controller.system;

import com.storage.common.core.controller.BaseController;
import com.storage.common.core.domain.AjaxResult;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.core.page.TableDataInfo;
import com.storage.common.enums.OrderType;
import com.storage.common.enums.ProcurementType;
import com.storage.common.enums.RoleType;
import com.storage.common.utils.DateUtils;
import com.storage.framework.web.OperationContext;
import com.storage.framework.web.enums.RequestOperation;
import com.storage.system.domain.StorageProcurementOrder;
import com.storage.system.domain.StorageShopOrder;
import com.storage.system.domain.StorageUser;
import com.storage.system.service.IStorageProcurementOrderService;
import com.storage.system.service.IStorageShopOrderService;
import com.storage.system.vo.SellDetailInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * 订单 信息操作处理
 *
 * @author ruoyi
 * @date 2019-08-26
 */
@Api(tags = "订单相关接口")
@RestController
public class StorageOrderController extends BaseController {

    @Autowired
    private IStorageProcurementOrderService storageProcurementOrderService;

    @Autowired
    private IStorageShopOrderService storageShopOrderService;

    /**
     * 查询采购/订购 订单列表
     */
    @ApiOperation(value = "查询采购/订购 订单列表")
    @GetMapping("/system/order/procurement/list")
    @ResponseBody
    public TableDataInfo procurementList(@RequestOperation OperationContext context,
                                         StorageProcurementOrder procurementOrder,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startDate,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate,
                                         @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                         @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (startDate != null) {
            procurementOrder.setStartTime(startDate);
        }
        if (endDate != null) {
            procurementOrder.setEndTime(endDate);
        }
        ServiceResponse<TableDataInfo> response = storageProcurementOrderService.selectStorageProcurementOrderList(context.getStorageUser(), procurementOrder, pageNum, pageSize);
        return response.getData();
    }

    /**
     * 查询等待我审批的订单 - 别人来采购我
     */
    @ApiOperation(value = "查询等待我审批的订单 - 别人来采购我")
    @GetMapping("/system/order/provider/wait/confirm/list")
    @ResponseBody
    public TableDataInfo waitConfirmOtherApplicationOrderList(@RequestOperation OperationContext context,
                                                              @RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        StorageUser user = context.getStorageUser();
        // 拼接参数
        StorageProcurementOrder procurementOrder = new StorageProcurementOrder();
        Long canOperationUserId = RoleType.getOperationUserId(user.getRole(), user.getId(), user.getShopId());
        procurementOrder.setProvideUserId(canOperationUserId);
        procurementOrder.setOrderStatus(OrderType.START_ORDER.getValue());

        ServiceResponse<TableDataInfo> response = storageProcurementOrderService.selectStorageProcurementOrderList(context.getStorageUser(), procurementOrder, pageNum, pageSize);
        return response.getData();
    }

    /**
     * 查询等待我确认的订单 - 我向别人放弃采购申请,别人同意了以后等待我再次确认
     */
    @ApiOperation(value = "查询等待我确认的订单 - 我向别人发起采购申请,别人同意了以后等待我再次确认")
    @GetMapping("/system/order/application/wait/confirm/list")
    @ResponseBody
    public TableDataInfo waitConfirmMyApplicationOrderList(@RequestOperation OperationContext context,
                                                           @RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        StorageUser user = context.getStorageUser();
        // 拼接查询参数
        StorageProcurementOrder procurementOrder = new StorageProcurementOrder();
        Long canOperationUserId = RoleType.getOperationUserId(user.getRole(), user.getId(), user.getShopId());
        procurementOrder.setApplicationUserId(canOperationUserId);
        procurementOrder.setOrderStatus(OrderType.PROVIDER_ACCEPT.getValue());

        ServiceResponse<TableDataInfo> response = storageProcurementOrderService.selectStorageProcurementOrderList(context.getStorageUser(), procurementOrder, pageNum, pageSize);
        return response.getData();
    }


    /**
     * 被采购方确认订单 或者 拒绝订单
     */
    @ApiOperation(value = " 被采购方确认订单 或者 拒绝订单")
    @PostMapping("/system/order/provider/confirm/order")
    @ResponseBody
    public AjaxResult purchasedPartyChangeOrderStatus(@RequestOperation OperationContext context,
                                                      @RequestBody StorageProcurementOrder procurementOrder) {
        if (procurementOrder.getOrderStatus() != OrderType.PROVIDER_ACCEPT.getValue() && procurementOrder.getOrderStatus() != OrderType.PROVIDER_REFUSE.getValue()) {
            return AjaxResult.error("非法的订单状态");
        }

        ServiceResponse<StorageProcurementOrder> response = storageProcurementOrderService.updateStorageProcurementOrder(context.getStorageUser(), procurementOrder);
        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return AjaxResult.success("操作成功");
    }


    /**
     * 采购方确认订单 或者 拒绝订单
     */
    @ApiOperation(value = "采购方确认订单 或者 拒绝订单")
    @PostMapping("/system/order/application/confirm/order")
    @ResponseBody
    public AjaxResult purchasePartyChangeOrderStatus(@RequestOperation OperationContext context,
                                                     @RequestBody StorageProcurementOrder procurementOrder) {
        if (procurementOrder.getOrderStatus() != OrderType.APPLICATION_ACCEPT.getValue() && procurementOrder.getOrderStatus() != OrderType.APPLICATION_REFUSE.getValue()) {
            return AjaxResult.error("非法的订单状态");
        }
        StorageProcurementOrder updateObj = new StorageProcurementOrder();
        updateObj.setOrderStatus(procurementOrder.getOrderStatus());
        if (procurementOrder.getOrderStatus() == OrderType.APPLICATION_ACCEPT.getValue()) {
            // 采购方再次确认订单以后就代表该订单确定下来了
            updateObj.setOrderStatus(OrderType.ORDER_SUCCESS.getValue());
        }

        updateObj.setId(procurementOrder.getId());
        updateObj.setActualPaymentAmount(procurementOrder.getActualPaymentAmount());
        ServiceResponse<StorageProcurementOrder> response = storageProcurementOrderService.updateStorageProcurementOrder(context.getStorageUser(), updateObj);

        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 用户发起申请 - 采购/订购订单
     */
    @ApiOperation(value = "用户发起申请 - 采购/订购订单")
    @PostMapping("/system/order/procurement/userApplication")
    @ResponseBody
    public AjaxResult userApplicationOrder(@RequestOperation OperationContext context,
                                           @RequestBody StorageProcurementOrder procurementOrder) {

        StorageUser user = context.getStorageUser();
        // 新建订单设置订单申请人相关信息
        Long canOperationUserId = RoleType.getOperationUserId(user.getRole(), user.getId(), user.getShopId());
        Integer applicationType = RoleType.getOwnerType(user.getRole());
        if (procurementOrder.getApplicationUserId() == null) {
            procurementOrder.setApplicationUserId(canOperationUserId);
        }
        if (procurementOrder.getApplicationType() == null) {
            procurementOrder.setApplicationType(applicationType);
        }

        procurementOrder.setProcurementType(ProcurementType.USER_APPLICATION.getValue());
        ServiceResponse<StorageProcurementOrder> response = storageProcurementOrderService.updateStorageProcurementOrder(user, procurementOrder);
        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return AjaxResult.success();
    }

    /**
     * 上级直接发货
     */
    @ApiOperation(value = "上级直接发货")
    @PostMapping("/system/order/procurement/agentSend")
    @ResponseBody
    public AjaxResult agentSendOrder(@RequestOperation OperationContext context,
                                     @RequestBody StorageProcurementOrder procurementOrder) {
        ServiceResponse<StorageProcurementOrder> response = storageProcurementOrderService.agentSendOrder(context.getStorageUser(), procurementOrder);

        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return AjaxResult.success(response.getData());
    }


    /**
     * 更新采购/订购订单状态
     */
    @ApiOperation(value = "更新采购/订购订单状态")
    @PostMapping("/system/order/procurement/save")
    @ResponseBody
    public AjaxResult editProcurementSave(@RequestOperation OperationContext context,
                                          @RequestBody StorageProcurementOrder procurementOrder) {
        ServiceResponse<StorageProcurementOrder> response = storageProcurementOrderService.updateStorageProcurementOrder(context.getStorageUser(), procurementOrder);

        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return AjaxResult.success();
    }

    /**
     * 查询店铺 订单列表
     */
    @ApiOperation(value = "查询店铺 订单列表")
    @GetMapping("/system/order/shop/list")
    @ResponseBody
    public AjaxResult shopList(@RequestOperation OperationContext context,
                               StorageShopOrder shopOrder,
                              @RequestParam(value = "pageNum", required = false) Integer pageNum,
                              @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        ServiceResponse<TableDataInfo> response = storageShopOrderService.selectStorageShopOrderList(context.getStorageUser(), shopOrder, pageNum, pageSize);
        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return AjaxResult.success(response.getData());
    }

    /**
     * 查询店铺 商品销售数据列表
     */
    @ApiOperation(value = "查询店铺 商品销售数据列表")
    @GetMapping("/system/order/shop/sell/detail")
    @ResponseBody
    public AjaxResult getShopSellDetail(@RequestOperation OperationContext context,
                                        StorageShopOrder shopOrder,
                                       @RequestParam(required = false) String startTime,
                                       @RequestParam(required = false) String endTime,
                                       @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                       @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Date startTimeDate = null;
        try {
            startTimeDate = DateUtils.convertStrToDate(startTime, "yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            logger.warn("", e);
        }
        Date endTimeDate = null;
        try {
            endTimeDate = DateUtils.convertStrToDate(endTime, "yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            logger.warn("", e);
        }

        if (shopOrder.getShopId()==null) {
            return AjaxResult.error("店铺id不能为空");
        }

        ServiceResponse<TableDataInfo> response = storageShopOrderService.getShopSellDetail(context.getStorageUser(), shopOrder, startTimeDate, endTimeDate, pageNum, pageSize);
        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return AjaxResult.success(response.getData());
    }

    /**
     * 保存店铺订单
     */
    @ApiOperation(value = "保存店铺订单")
    @PostMapping("/system/order/shop/save")
    @ResponseBody
    public AjaxResult editShopSave(@RequestOperation OperationContext context,
                                   @RequestBody StorageShopOrder shopOrder) {
        return storageShopOrderService.updateStorageShopOrder(context.getStorageUser(), shopOrder);
    }

    /**
     * 查询当前营业额和销售数量 v2.0
     */
    @ApiOperation(value = "查询店铺销售订单列表")
    @GetMapping("/system/order/sell/detail")
    @ResponseBody
    public AjaxResult shopOrderHomePageList(@RequestOperation OperationContext context,
                                            StorageShopOrder storageShopOrder,
                                            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startDate,
                                            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate) {
        if (storageShopOrder.getShopId() == null) {
            return AjaxResult.success("店铺id不能为空");
        }

        if (startDate != null) {
            storageShopOrder.setStartTime(startDate);
        }
        if (endDate != null) {
            storageShopOrder.setEndTime(endDate);
        }

        ServiceResponse<List<SellDetailInfo>> response = storageShopOrderService.queryShopHomePageData(context.getStorageUser(), storageShopOrder);
        return AjaxResult.success(response.getData());
    }

}
